package com.sky.service.impl;


import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.CategoryService;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.xmlbeans.impl.xb.xsdschema.impl.TotalDigitsDocumentImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO turnoverStatists(LocalDate begin, LocalDate end) {
         List<LocalDate> dateList = new ArrayList<>();
         dateList.add(begin);
         while(!begin.isEqual(end)){
             // 计算指定日期
             begin = begin.plusDays(1);
             dateList.add(begin);
         }
         List<Double> totalAmountList = new ArrayList<>();


        for(LocalDate date:dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            HashMap map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double totalAmount = orderMapper.totalAmount(map);
            totalAmount = totalAmount == null ? 0 : totalAmount;
            totalAmountList.add(totalAmount);
        }
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(totalAmountList, ","))
                .build();
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatists(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while(!begin.isEqual(end)){
            // 计算指定日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        for(LocalDate date:dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            HashMap map = new HashMap();

            map.put("end",endTime);
            Integer userCountTotal = userMapper.userCount(map);
            totalUserList.add(userCountTotal);
            map.put("begin",beginTime);
            Integer newUserCount =  userMapper.userCount(map);
            newUserList.add(newUserCount);
        }
        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO orderStatists(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while(!begin.isEqual(end)){
            // 计算指定日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> complieOrderList = new ArrayList<>();
        List<Integer> totalOrderList = new ArrayList<>();
        for(LocalDate date:dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            HashMap map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            Integer totalOrderCount = orderMapper.totalCount(map);
            map.put("status", Orders.COMPLETED);
            Integer complieOrderCount = orderMapper.totalCount(map);
            totalOrderList.add(totalOrderCount);
            complieOrderList.add(complieOrderCount);
        }
        Integer totalOrderCount = totalOrderList.stream().reduce(Integer::sum).get();
        Integer complieOrderCount = complieOrderList.stream().reduce(Integer::sum).get();
        Double orderCompletionRate = totalOrderCount == 0 ? 0 : (double) complieOrderCount / totalOrderCount * 100;
        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCompletionRate(orderCompletionRate)
                .totalOrderCount(totalOrderCount)
                .orderCountList(StringUtils.join(totalOrderList, ","))
                .validOrderCountList(StringUtils.join(complieOrderList, ","))
                .validOrderCount(complieOrderCount)
                .build();
    }

    /**
     * 销量统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO saleStatists(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> res = orderMapper.saleTopTen(beginTime,endTime);
        List<String> nameList = res.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = res.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    /**
     * 导出excel
     * @param response
     */
    @Override
    public void exportExcel(HttpServletResponse response) {
        //1.查询数据源
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);


        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN),LocalDateTime.of(end, LocalTime.MAX));
        //2.写入数据
        InputStream inStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            XSSFWorkbook excel = new XSSFWorkbook(inStream);
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //写入数据
            sheet.getRow(1).getCell(2).setCellValue("时间" + begin + "至" + end);
            sheet.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            sheet.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());
            sheet.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            sheet.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice());
            for(int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN),LocalDateTime.of(date, LocalTime.MAX));
                sheet.getRow(7 + i).getCell(1).setCellValue(date.toString());
                sheet.getRow(7 + i).getCell(2).setCellValue(businessDataVO.getTurnover());
                sheet.getRow(7 + i).getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                sheet.getRow(7 + i).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                sheet.getRow(7 + i).getCell(5).setCellValue(businessDataVO.getUnitPrice());
                sheet.getRow(7 + i).getCell(6).setCellValue(businessDataVO.getNewUsers());

            }
            //3.下载

            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            out.close();
            excel.close();
        } catch(Exception e) {
            e.printStackTrace();
        }


    }
}
